<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="发起时间" prop="useTime" style="width: 308px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="审批状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
                <el-option v-for="dict in approval_commit_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime" style="width: 308px">
              <el-date-picker
                v-model="createTimeRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['humanresource:hrMonthlyAssessmentResult:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['humanresource:hrMonthlyAssessmentResult:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['humanresource:hrMonthlyAssessmentResult:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['humanresource:hrMonthlyAssessmentResult:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="hrMonthlyAssessmentResultList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="发起人" align="center" prop="initialName" fixed="left"/>
        <el-table-column label="发起部门" align="center" prop="initialDeptName" fixed="left"/>
        <el-table-column label="发起时间" align="center" prop="initialTime" width="120" fixed="left">
          <template #default="scope">
            <span>{{ parseTime(scope.row.initialTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="考核人" align="center" prop="userName" />
        <el-table-column label="所属部门" align="center" prop="deptName" />
        <el-table-column label="职位" align="center" prop="onboardPosition" >
          <template #default="scope">
            <el-tooltip :content="scope.row.onboardPosition" placement="top" :disabled="!scope.row.onboardPosition">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.onboardPosition }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="审批内容" align="center" prop="approvalContent" >
          <template #default="scope">
            <el-tooltip :content="scope.row.approvalContent" placement="top" :disabled="!scope.row.approvalContent">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.approvalContent }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" >
          <template #default="scope">
            <el-tooltip :content="scope.row.remark" placement="top" :disabled="!scope.row.remark">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.remark }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="120" fixed="right">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审批状态" align="center" prop="status" fixed="right">
          <template #default="scope">
            <dict-tag :options="approval_commit_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="110">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['humanresource:hrMonthlyAssessmentResult:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['humanresource:hrMonthlyAssessmentResult:remove']"></el-button>
            </el-tooltip>
            <!-- 审批按钮 -->
            <el-tooltip content="提交审批" placement="top">
              <el-button
                link
                type="primary"
                icon="DocumentChecked"
                @click="openApprovalFlow(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改员工月度考核结果审批对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="900px" append-to-body>
      <el-form ref="hrMonthlyAssessmentResultFormRef" :model="form" :rules="rules" label-width="140px" label-position="left" style="padding: 20px 0 20px 24px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="发起人" prop="initialName">
              <el-input v-model="form.initialName" placeholder="请输入发起人" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="发起部门" prop="initialDeptName">
              <el-tree-select
                v-model="form.initialDeptName"
                :data="deptTree"
                placeholder="请选择发起部门"
                :props="{ label: 'label', value: 'id', children: 'children' }"
                check-strictly
                filterable
                :default-expand-all="true"
                style="width: 100%"
                @visible-change="handleVisibleChange"
              />
              </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="发起时间" prop="initialTime">
              <el-date-picker
                clearable
                v-model="form.initialTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择发起时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="考核人" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入考核人" readonly @click="openUserSelector()"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属部门" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入所属部门" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="职位" prop="onboardPosition">
              <el-input v-model="form.onboardPosition" placeholder="请输入职位" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审批内容" prop="approvalContent">
              <el-input v-model="form.approvalContent" placeholder="请输入审批内容" type="textarea" :rows="3"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" :rows="3"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 申请人选择对话框 -->
    <UserSelector
      v-model:visible="userSelectVisible"
      :title="userSelectTitle"
      :selected-user-ids="currentSelectedUserIds"
      :selected-user-names="currentSelectedUserNames"
      :multiple="isJoint"
      @confirmWithIds="handleUserSelectWithIds"
      @cancel="handleUserSelectCancel"
    />

    <!-- 审核流程配置对话框 --> 
    <ApprovalFlow v-model:visible="approvalFlowVisible" :business-type="'HR-PERFORMANCE-RESULT-AUDIT'"
      :business-id="auditIdForApproval" :key="auditIdForApproval" title="配置员工月度绩效考评结果审核流程" @confirm="handleApprovalConfirm"
      @cancel="handleApprovalCancel" />
  </div>
</template>

<script setup name="HrMonthlyAssessmentResult" lang="ts">
import { listHrMonthlyAssessmentResult, getHrMonthlyAssessmentResult, delHrMonthlyAssessmentResult, addHrMonthlyAssessmentResult, updateHrMonthlyAssessmentResult } from '@/api/general/humanresources/performance/result';
import { HrMonthlyAssessmentResultVO, HrMonthlyAssessmentResultQuery, HrMonthlyAssessmentResultForm } from '@/api/general/humanresources/performance/result/types';
import { resetApprovalStatus } from '@/components/ApprovalFlow/api';
import type { DeptTreeNode } from '@/api/general/administration/seal/types';
import { getDeptTree } from '@/api/general/administration/seal';
import { useUserStore } from '@/store/modules/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const hrMonthlyAssessmentResultList = ref<HrMonthlyAssessmentResultVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 用户信息
const userStore = useUserStore();

// 部门树初始化
const deptTree = ref<DeptTreeNode[]>([]);
const deptTreeSelectRef = ref();
// 引入数据字典
const { approval_commit_status } = toRefs<any>(proxy?.useDict('approval_commit_status'));

// 提交审核相关
const approvalFlowVisible = ref(false);
const currentSubmitAuditRow = ref<any>(null);
const auditIdForApproval = ref<string | number | undefined>(undefined);

// 时间选择器查询参数初始化
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const createTimeRange = ref<[DateModelType, DateModelType]>(['', '']);

// 申请人选择相关
const userSelectVisible = ref(false);
const userSelectTitle = ref('');
const isJoint = ref(false); 
const currentSelectedUserIds = ref('');
const currentSelectedUserNames = ref('');
const currentActualStage = ref<any>(null);
const currentSelectStageIndex = ref(-1);

const queryFormRef = ref<ElFormInstance>();
const hrMonthlyAssessmentResultFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 本地时间格式化函数
const formatLocalDate = (date = new Date()) => {
  const padZero = num => String(num).padStart(2, '0');
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`;
};

const initFormData: HrMonthlyAssessmentResultForm = {
  id: undefined,
  initialId: userStore.userId,
  initialName: userStore.name,
  initialDeptId: userStore.deptId,
  initialDeptName: userStore.deptName,
  initialTime: formatLocalDate(),
  userId: undefined,
  userName: undefined,
  deptId: undefined,
  deptName: undefined,
  onboardPosition: undefined,
  approvalContent: undefined,
  remark: undefined,
  status: undefined,
}
const data = reactive<PageData<HrMonthlyAssessmentResultForm, HrMonthlyAssessmentResultQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    initialId: undefined,
    initialDeptId: undefined,
    initialTime: undefined,
    userId: undefined,
    deptId: undefined,
    onboardPosition: undefined,
    approvalContent: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键不能为空", trigger: "blur" }
    ],
    initialName: [
      { required: true, message: '请输入发起人', trigger: 'blur' },
      { min: 1, max: 50, message: '长度应在 1 到 50 个字符之间', trigger: 'blur' }
    ],
    initialDeptName: [
      { required: true, message: '请选择发起部门', trigger: 'change' }
    ],
    initialTime: [
      { required: true, message: '请选择发起时间', trigger: 'change' }
    ],
    userName: [
      { required: true, message: '请选择考核人', trigger: 'blur' }
    ],
    deptName: [
      { required: true, message: '请输入所属部门', trigger: 'blur' }
    ],
    onboardPosition: [
      { required: true, message: '请输入职位', trigger: 'blur' },
      { max: 100, message: '职位名称不能超过 100 个字符', trigger: 'blur' }
    ],
    approvalContent: [
      { required: true, message: '请输入审批内容', trigger: 'blur' },
      { min: 1, max: 500, message: '审批内容长度应在 1 到 500 个字符之间', trigger: 'blur' }
    ],
    remark: [
      { required: false, message: '请输入备注', trigger: 'blur' },
      { max: 300, message: '备注不能超过 300 个字符', trigger: 'blur' }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询员工月度考核结果审批列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    if (dateRange.value?.length === 2) {
      params.params = {
        ...params.params,
        bUseTime: dateRange.value[0]?.toString(),
        eUseTime: dateRange.value[1]?.toString()
      };
    }
    if (createTimeRange.value?.length === 2) {
      params.params = {
        ...params.params,
        beginTime: createTimeRange.value[0]?.toString(),
        endTime: createTimeRange.value[1]?.toString()
      };
    }
    const res = await listHrMonthlyAssessmentResult(queryParams.value);
    hrMonthlyAssessmentResultList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取列表失败:', error);
    proxy?.$modal.msgError('获取列表失败');
  } finally {
    loading.value = false;
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  hrMonthlyAssessmentResultFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  createTimeRange.value = ['', ''];
  queryFormRef.value?.resetFields();
    queryParams.value.params = {
    bUseTime: undefined,
    eUseTime: undefined,
    beginTime: undefined,
    endTime: undefined
  };
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: HrMonthlyAssessmentResultVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加员工月度考核结果审批";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: HrMonthlyAssessmentResultVO) => {
  if (row.status != 4) {
    ElMessage.error("只能对审核不过的申请进行修改")
    return;
  }
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getHrMonthlyAssessmentResult(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改员工月度考核结果审批";
}

/** 提交按钮 */
const submitForm = () => {
  hrMonthlyAssessmentResultFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateHrMonthlyAssessmentResult(form.value).finally(() =>  buttonLoading.value = false);
         // 调用重置审核流程接口
        await resetApprovalStatus('HR-PERFORMANCE-MONTHLY-AUDIT', Number(form.value.id), '不可审核')
      } else {
        const res = await addHrMonthlyAssessmentResult(form.value).finally(() =>  buttonLoading.value = false);
        // 触发审核流程配置对话框
        auditIdForApproval.value = res.data;
        approvalFlowVisible.value = true;
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: HrMonthlyAssessmentResultVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除员工月度考核结果审批编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delHrMonthlyAssessmentResult(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('humanresource/hrMonthlyAssessmentResult/export', {
    ...queryParams.value
  }, `hrMonthlyAssessmentResult_${new Date().getTime()}.xlsx`)
}

// 下拉框打开时展开全部节点
const handleVisibleChange = (visible: boolean) => {
  if (visible) {
    // 展开全部节点（treeSelect 内部的 tree 是 el-tree 实例）
    setTimeout(() => {
      const tree = deptTreeSelectRef.value?.$refs?.tree;
       tree?.expandAll?.();
    }, 0);
  }
};

// 获取部门树
const fetchDeptTree = async () => {
  try {
    const res = await getDeptTree();
    const processNode = (node: any) => {
      if (node.children && node.children.length > 0) {
        // 有子节点 → 禁用，但允许展开
        node.disabled = true;
        node.children.forEach(processNode); // 递归处理子节点
      } else {
        // 叶子节点 → 可选
        node.disabled = false;
      }
    };
    if (Array.isArray(res.data)) {
      res.data.forEach(processNode);
    }
    deptTree.value = res.data;
  } catch (error) {
    console.error('获取部门树失败:', error);
    proxy?.$modal.msgError('获取部门树失败');
  }
};

/** 审核流程确认回调 */
const handleApprovalConfirm = async () => {
  try {
    ElMessage.success('工作日志审核流程提交成功');
    approvalFlowVisible.value = false;
    currentSubmitAuditRow.value = null;
    auditIdForApproval.value = undefined;
  } catch (error) {
    console.error('审核流程提交失败:', error);
    ElMessage.error('审核流程提交失败');
  }
};

/** 审核流程取消回调 */
const handleApprovalCancel = () => {
  approvalFlowVisible.value = false;
  currentSubmitAuditRow.value = null;
  auditIdForApproval.value = undefined;
  // 审核流程取消时，表单已经在submitCurrentWorklogs中重置了，这里不需要重复重置
};

// 打开审批弹窗
const openApprovalFlow = (row?: HrMonthlyAssessmentResultForm) => {
  if (row.status != 5){
    ElMessage.error('只能提交已导入的信息审批！');
    return;
  }
  auditIdForApproval.value = row.id;
  approvalFlowVisible.value = true;
};

// 打开选择框
const openUserSelector = () => {
  userSelectTitle.value = '选择接受人员';
  currentSelectedUserIds.value = String(form.value.userId);
  currentSelectedUserNames.value = form.value.userName;
  userSelectVisible.value = true;
  currentActualStage.value = null;
  currentSelectStageIndex.value = -100;
};

// 处理使用人或共同使用人选择确认
const handleUserSelectWithIds = (data: { users: any[]; userIds: string; userNames: string }) => {
  const u = data.users[0];
  form.value.userId = u.userId;
  form.value.userName = u.userName;
  form.value.deptId = u.deptId;
  form.value.deptName = u.deptName;
  handleUserSelectCancel();
};

// 取消选择
const handleUserSelectCancel = () => {
  currentActualStage.value = null;
  currentSelectStageIndex.value = -1;
  currentSelectedUserIds.value = '';
  currentSelectedUserNames.value = '';
  userSelectVisible.value = false;
};

onMounted(() => {
  getList();
  fetchDeptTree();
});
</script>
